﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNet.Edu.Entity;
using DotNet.Edu.Service;
using DotNet.EduWebApi.Models;
using DotNet.Extensions;
using DotNet.Helper;
using DotNet.Utility;

namespace DotNet.EduWebApi.Controllers
{
    public class LearningController : BaseApiController
    {
        /// <summary>
        /// 获取学员主界面信息
        /// </summary>
        /// <param name="userId">学员主键</param>
        [ApiCheck, HttpPost]
        public ActionResult GetMainInfo(string userId)
        {
            #region 参数验证解密

            if (userId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学员主键"));
            }

            var validResult = EncryptUtil.Decrypt(userId, "学员主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            userId = validResult.Data;

            #endregion

            var student = GetStudentById(userId);
            var model = new MainModel();
            model.Name = student.Name; //学员姓名
            model.WorkCategory = student.WorkCategoryId;
            model.WorkCategoryName = student.WorkCategoryName + "继续教育培训";
            model.Status = student.Status; //学员状态
            model.StatusName = student.StatusName; //学员状态名称

            var categoryModel = EduService.EduCategory.Get(student.WorkCategoryId);

            model.SystemTotalPeriod = categoryModel.EduTotalPeriod; //系统规定学时
            if (model.SystemTotalPeriod > 0)
            {
                model.SystemTotalPeriodName = DateTimeHelper.GetTimeStringHMS(model.SystemTotalPeriod);  //系统规定学时字符串
            }

            model.LearnTotalPeriod = student.TotalPeriod; //累计完成学时
            if (model.LearnTotalPeriod > 0)
            {
                model.LearnTotalPeriodName = DateTimeHelper.GetTimeStringHMS(model.LearnTotalPeriod); //累计完成学时字符串
            }
            model.TodayPeriod = EduService.PeriodDetails.GetStudentDayPeriod(userId, DateTime.Now.Date); ; //今日完成学时
            if (model.TodayPeriod > 0)
            {
                model.TodayPeriodName = DateTimeHelper.GetTimeStringHMS(model.TodayPeriod); //今日完成学时字符串
            }

            var lastPeriod = EduService.PeriodDetails.GetStudentLast(userId);
            if (lastPeriod != null)
            {
                model.LastLearnTime = DateTimeHelper.FormatDateHasSecond(lastPeriod.CreateDateTime); ; //上次学习时间
            }
            model.Progress = Math.Round(Convert.ToDecimal(student.TotalPeriod) / model.SystemTotalPeriod * 100, 0).ToInt(); //学习进度
                                                                                                                            //课件列表
            model.CoursewareList = EduService.StudentCoursewarePeriod.GetList(userId, student.WorkCategoryId)
                ?? new List<StudentCoursewarePeriodView>();
            for (var index = 0; index < model.CoursewareList.Count; index++)
            {
                var item = model.CoursewareList[index];
                item.ImageUrl = UploadHelper.GetSiteUrl($"/www/img/kc/{index + 1}.jpg");
            }
            return Json(new BoolMessageData(model));
        }

        ///// <summary>
        ///// 学习检测
        ///// </summary>
        ///// <param name="userId">学员主键</param>
        ///// <param name="coursewareId">课件主键</param>
        //[ApiCheck, HttpPost]
        //public ActionResult LearnCheck(string userId, string coursewareId)
        //{
        //    #region 参数验证解密

        //    if (userId.IsEmpty())
        //    {
        //        return Json(new BoolMessage(false, "请指定学员主键"));
        //    }

        //    var validResult = EncryptUtil.Decrypt(userId, "学员主键");
        //    if (!validResult.Success)
        //    {
        //        return Json(validResult);
        //    }

        //    userId = validResult.Data;


        //    if (coursewareId.IsEmpty())
        //    {
        //        return Json(new BoolMessage(false, "请指定课件主键"));
        //    }

        //    validResult = EncryptUtil.Decrypt(coursewareId, "课件主键");
        //    if (!validResult.Success)
        //    {
        //        return Json(validResult);
        //    }

        //    coursewareId = validResult.Data;

        //    #endregion

        //    var result = LearnCheckCore(userId,coursewareId);
        //    return Json(result);
        //}

        /// <summary>
        /// 获取课件信息
        /// </summary>
        /// <param name="userId">学员主键</param>
        /// <param name="coursewareId">课件主键</param>
        [ApiCheck, HttpPost]
        public ActionResult GetCoursewareInfo(string userId, string coursewareId)
        {
            #region 参数验证解密

            if (userId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学员主键"));
            }

            var validResult = EncryptUtil.Decrypt(userId, "学员主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            userId = validResult.Data;


            if (coursewareId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定课件主键"));
            }

            validResult = EncryptUtil.Decrypt(coursewareId, "课件主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            coursewareId = validResult.Data;

            #endregion

            var categoryId = EduService.Student.GetWorkCategoryId(userId);

            var coursewareEntity = EduService.Courseware.Get(coursewareId);
            var coursewareModel = new CoursewareModel
            {
                Id = coursewareEntity.Id,
                Name = coursewareEntity.Name,
                CourseType = coursewareEntity.CourseType,
                Category = EduService.EduCategory.Get(categoryId),
                Check = LearnCheckCore(userId, coursewareId),
                Period = coursewareEntity.Period,
                Validate = GetValidateModel(),
                Details = EduService.CoursewareDetails.GetList(coursewareId)
            };
            foreach (var item in coursewareModel.Details)
            {
                item.Url = UploadHelper.GetUploadUrl(item.Url);
            }
            return Json(new BoolMessageData(coursewareModel));
        }

        /// <summary>
        /// 获取独立验证信息
        /// </summary>
        [ApiCheck, HttpPost]
        public ActionResult GetValidateInfo()
        {
            var vm = GetValidateModel();
            return Json(new BoolMessageData(vm));
        }

        /// <summary>
        /// 学员签到签退验证
        /// </summary>
        /// <param name="userId">学员主键</param>
        /// <param name="validateId">验证问题主键</param>
        /// <param name="coursewareId">课件主键</param>
        /// <param name="answer">学员答案</param>
        /// <param name="recordType">验证类型 1 签到 2 签退 3 随机验证</param>
        [ApiCheck, HttpPost]
        public ActionResult Validate(string userId, string coursewareId, string validateId,
            string answer, string recordType)
        {
            #region 参数验证解密

            #region userId
            if (userId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学员主键"));
            }

            var validResult = EncryptUtil.Decrypt(userId, "学员主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            userId = validResult.Data;
            #endregion

            #region coursewareId
            if (coursewareId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定课件主键"));
            }

            validResult = EncryptUtil.Decrypt(coursewareId, "课件主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            coursewareId = validResult.Data;
            #endregion

            #region validateId
            if (validateId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定验证问题"));
            }

            validResult = EncryptUtil.Decrypt(validateId, "验证问题");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            validateId = validResult.Data;
            #endregion

            #region answer
            if (answer.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学员答案"));
            }

            validResult = EncryptUtil.Decrypt(answer, "学员答案");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            answer = validResult.Data;
            #endregion

            #region device
            if (recordType.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定验证类型"));
            }

            validResult = EncryptUtil.Decrypt(recordType, "验证类型");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            recordType = validResult.Data;
            if (!recordType.Equals("1") && !recordType.Equals("2") && !recordType.Equals("3"))
            {
                return Json(new BoolMessage(false, "无效的验证类型"));
            }
            #endregion

            #endregion

            var result = false;
            var validEntity = EduService.StudentValidate.Get(validateId);
            if (validEntity.Answer.Equals(answer, StringComparison.OrdinalIgnoreCase))
            {
                result = true;
            }

            var student = GetStudentById(userId);
            var log = new LessonLog();
            log.Id = StringHelper.Guid();
            log.StudentId = student.Id;
            log.CoursewareId = coursewareId;
            log.CoursewareName = EduService.Courseware.GetName(coursewareId);
            log.WorkType = student.WorkCategoryId;
            log.WorkTypeName = student.WorkCategoryName;
            log.CreateDateTime = DateTime.Now;
            log.RecordType = recordType.ToInt();
            log.Result = result;
            EduService.LessonLog.Create(log);
            return Json(new BoolMessage(result, result ? "验证成功" : "验证失败"));
        }

        /// <summary>
        /// 学习签退提交
        /// </summary>
        /// <param name="userId">学员主键</param>
        /// <param name="coursewareId">课件主键</param>
        /// <param name="period">学习时长</param>
        /// <param name="signInDateTime">签到时间</param>
        /// <param name="device">学习设备</param>
        /// <param name="loginIpAddr">学习IP</param>
        [ApiCheck, HttpPost]
        public ActionResult Commit(string userId, string coursewareId,
            string period, string signInDateTime, string device, string loginIpAddr)
        {
            #region 参数验证解密

            #region userId
            if (userId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学员主键"));
            }

            var validResult = EncryptUtil.Decrypt(userId, "学员主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            userId = validResult.Data;
            #endregion

            #region coursewareId
            if (coursewareId.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定课件主键"));
            }

            validResult = EncryptUtil.Decrypt(coursewareId, "课件主键");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            coursewareId = validResult.Data;
            #endregion

            #region period
            if (period.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学习时长"));
            }

            validResult = EncryptUtil.Decrypt(period, "学习时长");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            period = validResult.Data;
            #endregion

            #region signInDateTime
            if (signInDateTime.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定签到时间"));
            }

            validResult = EncryptUtil.Decrypt(signInDateTime, "签到时间");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            signInDateTime = validResult.Data;
            #endregion

            #region device
            if (device.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学习设备"));
            }

            validResult = EncryptUtil.Decrypt(device, "学习设备");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            device = validResult.Data;
            #endregion

            #region loginIpAddr
            if (loginIpAddr.IsEmpty())
            {
                return Json(new BoolMessage(false, "请指定学习IP"));
            }

            validResult = EncryptUtil.Decrypt(loginIpAddr, "学习IP");
            if (!validResult.Success)
            {
                return Json(validResult);
            }

            loginIpAddr = validResult.Data;
            #endregion

            #endregion

            var sDateTime = signInDateTime.ToDateTime();
            var periodNum = period.ToInt();
            //var now = DateTime.Now;
            //if ((now - sDateTime).TotalSeconds < periodNum)
            //{
            //    LogHelper.Log($"签到时间和学习时长不符,非法提交,现在时间:{now},提交时间:{sDateTime} ,提交时长:{periodNum}");
            //    return Json(new BoolMessage(false, "签到时间和学习时长不符,非法提交"));
            //}
            try
            {
                var student = GetStudentById(userId);
                if (student == null)
                {
                    return Json(new BoolMessage(false, "无效的学员"));
                }
                PeriodDetails entity = new PeriodDetails();
                entity.CoursewareId = coursewareId;
                entity.SchoolId = student.SchoolId;
                entity.SchoolName = student.SchoolName;
                entity.StudentId = student.Id;
                entity.StudentName = student.Name;
                entity.StudyCategory = device;
                entity.IPAddress = loginIpAddr;
                entity.SignInDateTime = sDateTime;
                entity.SignOutDateTime = DateTime.Now;
                entity.Period = periodNum;
                entity.CreateDateTime = DateTime.Now;
                entity.CreateDate = entity.CreateDateTime.Date;

                var categoryModel = EduService.EduCategory.Get(student.WorkCategoryId);
                EduService.PeriodDetails.Create(entity);
                EduService.StudentCoursewarePeriod.Save(entity.StudentId, entity.CoursewareId, entity.Period);
                var totalPeriod = EduService.StudentCoursewarePeriod.GetStudentPeriod(entity.StudentId);
                EduService.Student.UpdateTotalPeriod(entity.StudentId, totalPeriod, categoryModel.EduTotalPeriod);
                return Json(BoolMessage.True);
            }
            catch (Exception e)
            {
                return Json(new BoolMessage(false, e.Message.ReplaceEnter()));
            }
        }

        /// <summary>
        /// 验证图片
        /// </summary>
        /// <param name="id">验证问题主键</param>
        public ActionResult ValidateImage(string id)
        {
            //#region 参数验证解密

            //if (validateId.IsEmpty())
            //{
            //    return Json(new BoolMessage(false, "请指定验证主键"));
            //}

            //var validResult = EncryptUtil.Decrypt(validateId, "验证主键");
            //if (!validResult.Success)
            //{
            //    return Json(validResult);
            //}

            //validateId = validResult.Data;

            //#endregion

            var validEntity = EduService.StudentValidate.Get(id);
            if (validEntity == null)
            {
                return Content("无效的验证标识");
            }
            var msg = validEntity.Name;
            ValidateCodeDrawHelper v = new ValidateCodeDrawHelper();
            v.FontSize = 12;
            v.Padding = 5;
            var bmp = v.CreateImage(msg, false);
            return File(ImageHelper.ToArray(bmp), "image/png");
        }

        /// <summary>
        /// 学习检测
        /// </summary>
        /// <param name="userId">学员主键</param>
        /// <param name="coursewareId">课件主键</param>
        private BoolMessage LearnCheckCore(string userId, string coursewareId)
        {
            var student = GetStudentById(userId);
            var studentId = student.Id;

            if (student.Status == 3)
            {
                return new BoolMessage(false, "你正在准备考试,学习将不计时");
            }
            if (student.Status == 4)
            {
                return new BoolMessage(false, "你正在考试中,学习将不计时");
            }
            if (student.Status == 5)
            {
                return new BoolMessage(false, "你已完成本次继续教育,学习将不计时");
            }

            var categoryModel = EduService.EduCategory.Get(student.WorkCategoryId);
            int eduDayMaxPeriod = categoryModel.EduDayMaxPeriod;
            int studentDayMaxPeriod = EduService.PeriodDetails.GetStudentDayPeriod(studentId, DateTime.Now.Date);
            if (studentDayMaxPeriod >= eduDayMaxPeriod)
            {
                return new BoolMessage(false, "你已经完成今天最大学习时长,学习将不计时");
            }

            int eduCoursewarePeriod = EduService.Courseware.Get(coursewareId).Period;
            int studentCoursewarePeriod = EduService.StudentCoursewarePeriod.GetStudentCoursewarePeriod(studentId, coursewareId);
            if (studentCoursewarePeriod >= eduCoursewarePeriod)
            {
                return new BoolMessage(false, "本课件已经学习完成,学习将不计时");
            }

            int eduTotalPeriod = categoryModel.EduTotalPeriod;
            int studentTotalPeriod = student.TotalPeriod;
            if (studentTotalPeriod >= eduTotalPeriod)
            {
                return new BoolMessage(false, "课件已经全部完成,学习将不计时");
            }

            return BoolMessage.True;
        }

        /// <summary>
        /// 获取验证对象
        /// </summary>
        private object GetValidateModel()
        {
            var entity = EduService.StudentValidate.GetRandom();
            var list = new List<string>();
            if (entity.A.IsNotEmpty()) list.Add(entity.A);
            if (entity.B.IsNotEmpty()) list.Add(entity.B);
            if (entity.C.IsNotEmpty()) list.Add(entity.C);
            if (entity.D.IsNotEmpty()) list.Add(entity.D);

            var vm = new
            {
                id = entity.Id,
                name = entity.Name,
                url = UploadHelper.GetSiteUrl($"~/Learning/ValidateImage/{entity.Id}"),
                options = RandomHelper.RandomArray(list.ToArray())
            };
            return vm;
        }
    }
}